import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 所有的任务列表
    list: [],
    // 文本框的内容
    inputValue: 'aaa',
    // 下一个按钮
    nextId: 5,
    viewKey: 'all'
  },
  mutations: {
    initList(state,list){
      state.list = list
    },
    // 给state中的inputvalue赋值
    setInputValue(state,value){
      state.inputValue = value
    },
    // 添加列表项目
    addItem(state){
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    // 根据id删除相应的任务项目
    removeItem(state,id){
      // 根据id查询对应项的索引
      const i = state.list.findIndex(x => x.id === id)
      // 根据索引删除相应元素
      if(i !== -1){
        state.list.splice(i, 1)
      }
    },
    // 修改选中状态
    changeStatus(state,param){
      const i = state.list.findIndex(x => x.id === param.id)
      if(i !== -1){
        state.list[i].done = param.status
      }
    },
    // 清除已经完成的任务项
    cleanDone(state){
      state.list = state.list.filter(x => x.done === false)
    },
    // 修改
    changeViewKey(state,key){
      state.viewKey = key
    }
  },
  // 异步
  actions: {
    getList(context) {
      axios.get('/list.json').then(({data}) => {
        // console.log(data);
        context.commit('initList',data)
      })
    }
  },
  getters: {
    // 统计未完成任务的条数
    unDoneLength(state){
      return state.list.filter(x => x.done === false).length
    },
    infoList(state){
      if(state.viewKey === 'all'){
        return state.list
      }
      if(state.viewKey === 'undone'){
        return state.list.filter(x => !x.done)
      }
      if(state.viewKey === 'done'){
        return state.list.filter(x => x.done)
      }

      return state.list
    }
  },
  modules: {
  }
})
